<?php

$name = $_POST['name'];
$email = $_POST['email'];
$newpassword = $_POST['newpassword'];
$repeatnewpassword = $_POST['repeatnewpassword'];

$sql = "SELECT * FROM `user` WHERE `email` = '$email';";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
    print "<script language='javascript'>
        alert('E-mail already exists.');
        history.back();';
        </script>";
} else {
    if ($newpassword != "") {
        if ($newpassword != $repeatnewpassword) {
            print "<script language='javascript'>
                alert('The new password does not match with the repeated one.');
                history.back();';
                </script>";
        } else {
            $password = passwordmd5($newpassword);
            $sql = "INSERT INTO `user` (`password`, `name`, `date_in`,`email`) 
                VALUES ('$password', '$name', CURDATE(), '$email');";
            $result = mysql_query($sql);

            $sql = "SELECT * FROM `user` WHERE `email` = '$email' AND `password` = '$password';";
            $result = mysql_query($sql);
            if (mysql_num_rows($result) == 1) {
                $row = mysql_fetch_assoc($result);

                $_SESSION['logged'] = TRUE;
                $_SESSION['email'] = $email;
                $_SESSION['id'] = $row['id'];
                $_SESSION['name'] = $row['name'];
                $_SESSION['level'] = $row['level'];

                print "<script language='javascript'>
                window.location.href='./';
                </script>";
            } else {
                print "<script language='javascript'>
                alert('Your e-mail and password do not match.');
                window.location.href='?url=signup';
                </script>";
            }
        }
    } else {
        print "<script language='javascript'>
             alert('Password field is empty.');
             history.back();';
             </script>";
    }
}
?>
